//物流公司管理

interface ILogisticsManagentDetailViewModel {
    id?: string;
    /**
     * 物流公司名称
     */
    name: string;
    /**
     * 地址
     */
    address: string;
    /**
     * 管理员账户名
     */
    adminName: string;
    /**
     * 手机号
     */
    phoneNumber: string;
    /**
     * 管理员密码
     */
    adminPassword?: string;
    /**
     * 重复密码
     */
    reAdminPassword?: string;
    /**
     * 是否启用
     */
    isEnabled: boolean;
    /**
     * 控制管理员账户是否可编辑
     */
    isAdminNameEdit: boolean;
    /**
     * 省编号
     */
    provinceCode: string;
    /**
     * 市编号
     */
    cityCode: string;
    /**
     * 区编号
     */
    areaCode: string;
    /**
     * 点击事件
     */
    click: () => void;
}

interface ILogisticsManagentViewModel extends IBaseViewModel<ILogisticsManagentQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<LogisticsListItemResponse>;
    /**
     * 添加/编辑视图
     */
    detail: ILogisticsManagentDetailViewModel;
    /**
     * 添加物流方
     */
    addLogistics: () => void;
    /**
     * 编辑物流方
     */
    editLogistics: (id: string) => void;
    /**
     * 删除物流方
     */
    deleteLogistics: (id: string) => void;
    /**
     * 查询
     */
    query: () => void;
    heightA: number;
    /**是否自动选中省市区 */
    ischecked: boolean;

    CityList_logbox: Array<any>;
    AreaList_logbox: Array<any>;
}

interface ILogisticsManagentQueryTerms {
    /**
     * 单位名称
     */
    name: string;
    /**
     * 所属省份
     */
    provinceCode: string;
    /**
     * 所属城市
     */
    cityCode: string;
    /**
     * 所属区
     */
    areaCode: string;
}

class LogisticsManagentController extends ListController<ILogisticsManagentViewModel, ILogisticsManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<LogisticsListItemResponse>;

    constructor($scope: ILogisticsManagentViewModel,
        private areaService: areaService,
        private logisticsService: ILogisticsService,
        private $ngBootbox: BootboxService,
        private $location: ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.$scope.addLogistics = this.showAddLogisticsDialog;
        this.$scope.editLogistics = this.showEditLogisticsDialog;
        this.$scope.deleteLogistics = this.showDeleteLogisticsDialog;
        this.$scope.ischecked = false;
        this.$scope.queryTerms = {
            name: "",
            provinceCode: "-1",
            cityCode: "-1",
            areaCode: "-1"
        };

        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "名称", field: "name", enableColumnMenu: false },
                { name: "所属地区", field: "address", enableColumnMenu: false },
                { name: "用户数", field: 'userCount', enableColumnMenu: false },
                { name: "最后登录时间", field: 'lastLoginTime', enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" ng-click="grid.appScope.editLogistics(row.entity.id)"></a> <a class="primary fa fa-trash-o text-danger" ng-show="row.entity.userCount<=0" ng-click="grid.appScope.deleteLogistics(row.entity.id)"></a>', enableColumnMenu: false, width: '6%'
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }

        };

        this.$scope.query = this.query;
        this.query();
        /**
         * 这部分的验证可以自己开发扩展插件扩充官方的组件不需要这样单独定制化
         */

        //增加手机验证
        $.validator.addMethod("mobilePhone", (value: string, element, params) => {
            let length = value.length;
            let mobile = /^1[3|4|5|7|8][0-9]{9}$/;
            return length == 11 && mobile.test(value);
        }, "手机号码格式错误");

        //自定义验证
        $("#form").validate({
            rules: {
                reAdminPassword: {
                    minlength: 6,
                    equalTo: "#adminPassword"
                },
                adminPassword: {
                    minlength: 6
                }
            }
        });

        this.query();
    }

    loadData(queryTerms: ILogisticsManagentQueryTerms, skip: number, count: number): void {
        if (queryTerms.provinceCode == "-1") {
            queryTerms.provinceCode = "";
            queryTerms.cityCode = "";
            queryTerms.areaCode = "";
        } else if (queryTerms.cityCode == "-1") {
            queryTerms.cityCode = "";
            queryTerms.areaCode = "";
        }
        this.logisticsService.getList(queryTerms.name, queryTerms.provinceCode, queryTerms.cityCode,
            queryTerms.areaCode, skip, count).then(result => {
                this.$scope.gridOptions.totalItems = result.data.total;
                this.$scope.gridOptions.data = result.data.data;
                result.data.data.map((item, index) => item.index = skip++ + 1);
                this.$scope.heightA = result.data.data.length * 39 + 95;

                if (skip == 0) {
                    this.$scope.gridOptions.paginationCurrentPage = 1;
                }
                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
            });
    }

    /**
     * 弹出删除物流方对话框
     */
    showDeleteLogisticsDialog = (id: string) => {
        this.$ngBootbox.confirm("确定删除该数据吗？").then(e => {
            this.logisticsService.delete(id).then(result => {
                this.reload();
            });
        });
    }

    /**
     * 弹出添加物流方对话框
     */
    showAddLogisticsDialog = () => {
        this.$scope.title = "添加物流公司";
        this.$scope.ischecked = false;
        this.$scope.CityList_logbox = [];
        this.$scope.AreaList_logbox = [];
        $('#adminPasswordBox').addClass('required');
        $('#reAdminPasswordBox').addClass('required');
        this.$scope.detail = {
            name: "",
            provinceCode: "-1",
            cityCode: "-1",
            areaCode: "-1",
            address: "",
            adminName: "",
            phoneNumber: "",
            adminPassword: "",
            reAdminPassword: "",
            isEnabled: true,
            isAdminNameEdit: true,
            click: this.addLogistics
        };
    }

    addLogistics = () => {

        if (!$("#logisticsForm").valid()) { return };
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.logisticsService.add(
                this.$scope.detail.name,
                this.$scope.detail.provinceCode,
                this.$scope.detail.cityCode,
                this.$scope.detail.areaCode,
                this.$scope.detail.address,
                this.$scope.detail.adminName,
                this.$scope.detail.phoneNumber,
                this.$scope.detail.adminPassword,
                this.$scope.detail.reAdminPassword,
                this.$scope.detail.isEnabled
            ).then(result => {
                this.reload();
                $("#myModal").modal("hide");
            });
        });
    }

    /**
     * 弹出编辑物流方对话框
     */
    showEditLogisticsDialog = (id: string) => {
        this.$scope.ischecked = true;
        $('#adminPasswordBox').removeClass('required');
        $('#reAdminPasswordBox').removeClass('required');
        var validator = $('#logisticsForm').validate();
        validator.form();
        validator.hideErrors();
        this.$scope.detail.provinceCode = "-1";
        this.$scope.detail.cityCode = "-1";
        this.$scope.detail.areaCode = "-1";
        $(".error").removeClass("error");
        this.$scope.title = "编辑物流公司";
        
        this.logisticsService.getDetail(id).then(result => {
            this.areaService.getCity(result.data.province).then(res => {
                this.$scope.CityList_logbox = res.data.data;
            });
            this.areaService.getCounty(result.data.city).then(res => {
                this.$scope.AreaList_logbox = res.data.data;
            })
            this.$scope.detail = {
                id: id,
                name: result.data.name,
                provinceCode: result.data.province,
                cityCode: result.data.city,
                areaCode: result.data.area,
                address: result.data.address,
                adminName: result.data.adminName,
                phoneNumber: result.data.phoneNumber,
                isEnabled: result.data.isEnabled,
                isAdminNameEdit: false,
                click: this.editLogistics
            };
        });
    }

    editLogistics = () => {

        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.logisticsService.edit(
                this.$scope.detail.id,
                this.$scope.detail.name,
                this.$scope.detail.provinceCode,
                this.$scope.detail.cityCode,
                this.$scope.detail.areaCode,
                this.$scope.detail.address,
                this.$scope.detail.phoneNumber,
                this.$scope.detail.adminPassword,
                this.$scope.detail.reAdminPassword,
                this.$scope.detail.isEnabled
            ).then(result => {
                this.reload();
                $("#myModal").modal("hide");
            });
        });
    }
}

angular.module("tms").controller("logisticsManagentController", ["$scope",
    "areaService",
    "logisticsService", "$ngBootbox", "$location", LogisticsManagentController]);